package com.cmf.filter;
import com.alibaba.fastjson.JSON;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: cmf
 * @Date: 2025/8/28 13:23
 * @Version: v1.0.0
 * @Description: 登录检查过滤器，用于验证用户是否已登录
 **/
@WebFilter(urlPatterns = "/*")
@Order(1)
public class CheckLoginFilter implements Filter {

    // 路径匹配器
    private static final  AntPathMatcher antPathMatcher = new AntPathMatcher();

    // 不需要登录检查的路径
    private static final List<String> EXCLUDE_PATHS = Arrays.asList("/reggie-api/employee/login", "/reggie-api/employee/logout", "/reggie-api/employee/register", "/reggie-api/employee/sendMsg", "/user/login", "/user/sendMsg", "/user/register", "/reggie-api/common/**", "/reggie-api/backend/**", "/reggie-api/front/**", "/reggie-api/doc.html", "/reggie-api/webjars/**", "/reggie-api/swagger-resources", "/reggie-api/v2/api-docs");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        // 获取请求路径
        String requestURI = httpServletRequest.getRequestURI();

        if (check(requestURI)) {
            // 不需要登录检查，继续处理请求
            chain.doFilter(request, response);
            return;
        }

        
        // 检查session中的employee属性
        Long employee = (Long) httpServletRequest.getSession().getAttribute("employee");
        if (employee == null) {
            // 用户未登录，返回401状态码
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "未授权");
            httpServletResponse.getWriter().write(JSON.toJSONString(result));
            return;
        }
        
        // 用户已登录，继续处理请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private boolean check(String requestURI) {
        for (String path : EXCLUDE_PATHS) {
            if (antPathMatcher.match(path, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
